package com.itheima.bakery.demos.web.service.impl;
import com.itheima.bakery.demos.web.Repositories.OrderRepository;
import com.itheima.bakery.demos.web.model.Order;
import com.itheima.bakery.demos.web.model.User;
import com.itheima.bakery.demos.web.Repositories.UserRepository;
import com.itheima.bakery.demos.web.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.itheima.bakery.demos.web.Repositories.OrderRepository;
import java.util.List;
import java.util.Optional;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;
    private final OrderRepository orderRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository, PasswordEncoder passwordEncoder,OrderRepository orderRepository) {
        this.userRepository = userRepository;
        this.passwordEncoder = passwordEncoder;
        this.orderRepository = orderRepository;
    }

    @Override
    public List<User> findAllUsers() {
        return userRepository.findAll();
    }

    @Override
    public Optional<User> findUserById(Integer id) {
        return userRepository.findById(id);
    }

    @Override
    public User saveUser(User user) {
        // 检查密码是否为空或包含空格
        String password = user.getPassword();
        if (password == null || password.trim().isEmpty() || password.contains(" ")) {
            throw new IllegalArgumentException("密码不能为空且不能包含空格");
        }

        // 直接保存未加密的密码
        return userRepository.save(user);
    }

    @Override
    public void deleteUser(Integer id) {
        userRepository.deleteById(id);
    }

    @Override
    public Optional<User> findUserByEmail(String email) {
        return userRepository.findByEmail(email); // 调用 repository 的方法
    }

    @Override
    public List<Order> findOrdersByUserId(Integer userId) {
        return orderRepository.findByUserID(userId);
    }
}